package com.lemon.android.http;


import android.util.Base64;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class AesEncryptor {

    private static final String password = "Bar12345Bar87690"; // 128 bit key
    private static final String initVector = "RandomInitVector"; // 16 bytes IV

    public static String encrypt(String value) {
        return encrypt(password, initVector, value);
    }

    public static String decrypt(String encrypted) {
        return decrypt(password, initVector, encrypted);
    }

    private static String encrypt(String key, String initVector, String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(
                    initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"),
                    "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(value.getBytes());

            String str = Base64.encodeToString(encrypted, Base64.NO_WRAP);
            if (str != null && str.length() == 22) {
                str = str + "==";
            }
            return str;
            // return Base64.encodeBase64URLSafeString(encrypted)
            // return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    private static String decrypt(String key, String initVector,
                                  String encrypted1) {
        try {
            IvParameterSpec iv = new IvParameterSpec(
                    initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"),
                    "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            if (encrypted1 != null && encrypted1.length() == 24) {
                encrypted1 = encrypted1.substring(0, 22);
            }
            //byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted1));
            byte[] original = cipher.doFinal(Base64.decode(encrypted1, Base64.NO_WRAP));
            return new String(original, "UTF-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

}